import React, { useState, useEffect } from 'react';
import { Card, Checkbox, Radio, Button, Typography, Space, message, Divider, Spin } from 'antd';
import { ExperimentOutlined, SendOutlined, ReloadOutlined, LoadingOutlined } from '@ant-design/icons';
import deepseekApiService from '@/services/deepseekApi';
import './index.less';

const { Title, Text } = Typography;
const { Group: CheckboxGroup } = Checkbox;
const { Group: RadioGroup } = Radio;

interface FlavorSelection {
  malt: string[];
  hops: string[];
  yeast: string[];
  mouthfeel: string;
  alcohol: string;
}

const WineRecommendation: React.FC = () => {
  const [selections, setSelections] = useState<FlavorSelection>({
    malt: [],
    hops: [],
    yeast: [],
    mouthfeel: '',
    alcohol: '',
  });
  
  const [loading, setLoading] = useState(false);
  const [recommendation, setRecommendation] = useState<string>('');
  const [hasSelection, setHasSelection] = useState(false);
  const [isStreaming, setIsStreaming] = useState(false);

  // 精酿啤酒风味选项
  const flavorOptions = {
    malt: [
      '焦糖', '巧克力', '咖啡', '烤面包', '饼干', '蜂蜜', '太妃糖', '坚果'
    ],
    hops: [
      '柑橘', '花香', '松香', '草本', '热带水果', '辛辣', '葡萄柚', '柠檬'
    ],
    yeast: [
      '果香', '香蕉', '丁香', '胡椒', '酸味', '野性', '面包', '酯香'
    ],
    mouthfeel: [
      { label: '清爽轻盈', value: '清爽轻盈' },
      { label: '醇厚饱满', value: '醇厚饱满' },
      { label: '丝滑平衡', value: '丝滑平衡' },
      { label: '干燥清脆', value: '干燥清脆' },
      { label: '厚重复杂', value: '厚重复杂' },
    ],
    alcohol: [
      { label: '低度 (3-5%)', value: '低度(3-5%)' },
      { label: '中度 (5-7%)', value: '中度(5-7%)' },
      { label: '高度 (7-12%)', value: '高度(7-12%)' },
      { label: '无特殊要求', value: '无特殊要求' },
    ],
  };

  // 检查是否有选择
  useEffect(() => {
    const hasAnySelection = 
      selections.malt.length > 0 ||
      selections.hops.length > 0 ||
      selections.yeast.length > 0 ||
      selections.mouthfeel !== '' ||
      selections.alcohol !== '';
    
    setHasSelection(hasAnySelection);
  }, [selections]);

  // 获取AI推荐 - 支持流式响应
  const getRecommendation = async () => {
    if (!hasSelection) {
      message.warning('请先选择您的风味偏好');
      return;
    }

    setLoading(true);
    setIsStreaming(true);
    setRecommendation('');

    try {
      const prompt = deepseekApiService.buildRecommendationPrompt(selections);
      
      // 使用流式API获取推荐
      await deepseekApiService.getWineRecommendationStream(
        prompt,
        (chunk: string) => {
          // 实时更新推荐内容
          setRecommendation(prev => prev + chunk);
        }
      );
      
      message.success('推荐获取成功！');
    } catch (error) {
      console.error('推荐请求失败:', error);
      // 错误处理已在service中完成
    } finally {
      setLoading(false);
      setIsStreaming(false);
    }
  };

  // 重置选择
  const resetSelections = () => {
    setSelections({
      malt: [],
      hops: [],
      yeast: [],
      mouthfeel: '',
      alcohol: '',
    });
    setRecommendation('');
    message.info('已重置所有选择');
  };

  return (
    <div className="wine-recommendation">
      <div className="wine-recommendation-header">
        <Title level={1} className="page-title">
          <ExperimentOutlined className="title-icon" />
          AI精酿啤酒推荐
        </Title>
        <Text className="page-subtitle">
          选择您喜欢的风味特征，让AI为您推荐完美匹配的精酿啤酒
        </Text>
      </div>

      <div className="wine-recommendation-content">
        <Card 
          className="selection-card"
          title={
            <Space>
              <ExperimentOutlined />
              风味偏好选择
            </Space>
          }
        >
          <div className="flavor-sections">
            {/* 麦芽风味 */}
            <div className="flavor-section">
              <Title level={4} className="section-title">🌾 麦芽风味</Title>
              <div className="flavor-checkbox-group">
                <CheckboxGroup
                  options={flavorOptions.malt}
                  value={selections.malt}
                  onChange={(values) => setSelections(prev => ({ ...prev, malt: values as string[] }))}
                />
              </div>
            </div>

            <Divider />

            {/* 酒花风味 */}
            <div className="flavor-section">
              <Title level={4} className="section-title">🌿 酒花风味</Title>
              <div className="flavor-checkbox-group">
                <CheckboxGroup
                  options={flavorOptions.hops}
                  value={selections.hops}
                  onChange={(values) => setSelections(prev => ({ ...prev, hops: values as string[] }))}
                />
              </div>
            </div>

            <Divider />

            {/* 酵母风味 */}
            <div className="flavor-section">
              <Title level={4} className="section-title">🍺 酵母风味</Title>
              <div className="flavor-checkbox-group">
                <CheckboxGroup
                  options={flavorOptions.yeast}
                  value={selections.yeast}
                  onChange={(values) => setSelections(prev => ({ ...prev, yeast: values as string[] }))}
                />
              </div>
            </div>

            <Divider />

            {/* 口感偏好 */}
            <div className="flavor-section">
              <Title level={4} className="section-title">👅 口感偏好</Title>
              <div className="flavor-radio-group">
                <RadioGroup
                  options={flavorOptions.mouthfeel}
                  value={selections.mouthfeel}
                  onChange={(e) => setSelections(prev => ({ ...prev, mouthfeel: e.target.value }))}
                />
              </div>
            </div>

            <Divider />

            {/* 酒精度偏好 */}
            <div className="flavor-section">
              <Title level={4} className="section-title">🔥 酒精度偏好</Title>
              <div className="flavor-radio-group">
                <RadioGroup
                  options={flavorOptions.alcohol}
                  value={selections.alcohol}
                  onChange={(e) => setSelections(prev => ({ ...prev, alcohol: e.target.value }))}
                />
              </div>
            </div>
          </div>

          {/* 操作按钮 */}
          <div className="action-section">
            <Space size="large">
              <Button
                type="primary"
                size="large"
                icon={loading ? <LoadingOutlined /> : <SendOutlined />}
                onClick={getRecommendation}
                disabled={!hasSelection || loading}
                className="recommend-button"
              >
                {loading ? '正在获取推荐...' : '获取AI推荐'}
              </Button>
              <Button
                size="large"
                icon={<ReloadOutlined />}
                onClick={resetSelections}
                disabled={loading}
              >
                重置选择
              </Button>
            </Space>
          </div>
        </Card>

        {/* 推荐结果 */}
        {(loading || recommendation) && (
          <Card 
            className="result-card"
            title={
              <Space>
                <ExperimentOutlined />
                AI推荐结果
                {isStreaming && <span className="streaming-indicator">正在生成中...</span>}
              </Space>
            }
            style={{ marginTop: 24 }}
          >
            {loading && !recommendation ? (
              <div className="loading-container">
                <Spin 
                  size="large" 
                  indicator={<LoadingOutlined style={{ fontSize: 24 }} />}
                />
                <div className="loading-text">AI正在为您分析偏好并生成推荐...</div>
              </div>
            ) : (
              <div className="recommendation-content">
                <Text className="recommendation-text">
                  {recommendation.split('\n').map((line, index) => (
                    <React.Fragment key={index}>
                      {line}
                      {index < recommendation.split('\n').length - 1 && <br />}
                    </React.Fragment>
                  ))}
                  {isStreaming && <span className="typing-cursor">▋</span>}
                </Text>
              </div>
            )}
          </Card>
        )}
      </div>
    </div>
  );
};

export default WineRecommendation; 